import requests
import json
from typing import Dict, Optional

def exchange_authorization_code_for_token(
    client_id: str,
    client_secret: str,
    authorization_code: str,
    redirect_uri: str,
    code_verifier: str
) -> Optional[Dict]:
    """
    使用授权码换取访问令牌
    
    Args:
        client_id: 应用ID
        client_secret: 应用密钥
        authorization_code: 授权码
        redirect_uri: 重定向URI
        code_verifier: PKCE验证码
    
    Returns:
        包含token信息的字典，失败时返回None
    """
    url = "https://open.feishu.cn/open-apis/authen/v2/oauth/token"
    
    # 构建请求体
    payload = {
        "grant_type": "authorization_code",
        "client_id": client_id,
        "client_secret": client_secret,
        "code": authorization_code,
        "redirect_uri": redirect_uri,
        "code_verifier": code_verifier
    }
    
    headers = {
        "Content-Type": "application/json"
    }
    
    try:
        # 发送POST请求
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()  # 检查HTTP错误
        
        # 解析响应
        result = response.json()
        
        print(f"请求成功！状态码: {response.status_code}")
        print(f"响应内容: {json.dumps(result, indent=2, ensure_ascii=False)}")
        
        # 提取关键信息
        if "access_token" in result:
            print(f"\n访问令牌: \n{result['access_token']}")
        if "refresh_token" in result:
            print(f"刷新令牌: {result['refresh_token']}")
        if "expires_in" in result:
            print(f"过期时间: {result['expires_in']} 秒")
            
        return result
        
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"错误响应: {e.response.text}")
        return None
    except json.JSONDecodeError as e:
        print(f"JSON解析失败: {e}")
        return None
    except Exception as e:
        print(f"未知错误: {e}")
        return None

def main():
    """
    主函数 - 使用示例参数进行测试
    """
    # 使用你提供的参数
    client_id = "cli_a8f0b0443d77900d"
    client_secret = "2fvcFFlvS0B7HjsJMXa3Fhms7d8G83kn"
    authorization_code = "9BGlA9eabCAwAx5Ea0E68DeyzCBydxFz"
    redirect_uri = "https://open.feishu.cn/api-explorer/loading"
    code_verifier = "TxYmzM4PHLBlqm5NtnCmwxMH8mFlRWl_ipie3O0aVzo"
    
    print("开始OAuth授权码换取token...")
    print(f"客户端ID: {client_id}")
    print(f"重定向URI: {redirect_uri}")
    print(f"授权码: {authorization_code[:10]}...")
    print("-" * 50)
    
    # 执行token交换
    token_info = exchange_authorization_code_for_token(
        client_id=client_id,
        client_secret=client_secret,
        authorization_code=authorization_code,
        redirect_uri=redirect_uri,
        code_verifier=code_verifier
    )
    
    if token_info:
        print("\n✅ Token交换成功！")
        return token_info
    else:
        print("\n❌ Token交换失败！")
        return None

if __name__ == "__main__":
    main()